package com.xckj.teacher.ui.activity;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.trytry.android.update.UpdateCallback;
import com.trytry.android.update.UpdateManager;
import com.xckj.teacher.R;
import com.xckj.teacher.bean.UpdateBean;
import com.xckj.teacher.databinding.ActivityHomeBinding;
import com.xckj.teacher.event.OpenBottomTabEvent;
import com.xckj.teacher.event.UpdateEvent;
import com.xckj.teacher.framework.BaseActivity;
import com.xckj.teacher.global.Constant;
import com.xckj.teacher.iview.IUpdateView;
import com.xckj.teacher.presenter.MainPresenter;
import com.xckj.teacher.presenter.UpdatePresenter;
import com.xckj.teacher.ui.fragment.ClassFragment;
import com.xckj.teacher.ui.fragment.HomeFragment;
import com.xckj.teacher.ui.fragment.MyFragment;
import com.xckj.teacher.ui.fragment.TaskFragment;
import com.xckj.teacher.view.BottomMenuBar;
import com.xckj.teacher.view.UpdateVersionDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @Author: ChenYao
 * @Describe: 首页
 * @Date: 2024/4/10 21:18
 */
public class HomeActivity extends BaseActivity<ActivityHomeBinding> implements IUpdateView {
    private final Fragment[] mFragments = new Fragment[4];
    private final int indexTask = 1;
    private long exitTime = 0;

    @Override
    protected int loadLayout() {
        return R.layout.activity_home;
    }

    @Override
    protected int setStatusBarColor() {
        return R.color.home_top_status;
    }

    private String getFragmentTag(int index) {
        return "fragment_tab_" + index;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        int indexHome = 0;
        int indexClass = 2;
        int indexMy = 3;
        if (null != savedInstanceState) {
            Fragment homeTab = getSupportFragmentManager().findFragmentByTag(getFragmentTag(indexHome));
            if (null == homeTab) {
                homeTab = new HomeFragment();
            }
            Fragment taskTab = getSupportFragmentManager().findFragmentByTag(getFragmentTag(indexTask));
            if (null == taskTab) {
                taskTab = new TaskFragment();
            }
            Fragment classTab = getSupportFragmentManager().findFragmentByTag(getFragmentTag(indexClass));
            if (null == classTab) {
                classTab = new ClassFragment();
            }

            Fragment myTab = getSupportFragmentManager().findFragmentByTag(getFragmentTag(indexMy));
            if (null == myTab) {
                myTab = new MyFragment();
            }
            mFragments[indexHome] = homeTab;
            mFragments[indexTask] = taskTab;
            mFragments[indexClass] = classTab;
            mFragments[indexMy] = myTab;
        } else {
            mFragments[indexHome] = new HomeFragment();
            mFragments[indexTask] = new TaskFragment();
            mFragments[indexClass] = new ClassFragment();
            mFragments[indexMy] = new MyFragment();
        }
        dataBinding.bottomTabLayout.setCurrentItem(indexHome);
    }

    @Override
    protected void initData() {
        MainPresenter mainPresenter = new MainPresenter(this);
        mainPresenter.getUserInfo();
        UpdatePresenter presenter = new UpdatePresenter(this);
        presenter.update(getVersionName());
    }

    @Override
    protected void setListener() {
        dataBinding.bottomTabLayout.setOnTabSelectedListener(new BottomMenuBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                showHideFragment(prePosition, position);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }

            @Override
            public boolean onIntercept(int prePosition, int newPosition) {
                return false;
            }
        });
    }

    private void showHideFragment(int hide, int show) {
        FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
        Fragment showFragment = mFragments[show];
        Fragment hideFragment = mFragments[hide];
        if (hideFragment != showFragment && (null != getSupportFragmentManager().findFragmentByTag(getFragmentTag(hide)))) {
            trx.hide(hideFragment);
        }
        if (!showFragment.isAdded() && null == getSupportFragmentManager().findFragmentByTag(getFragmentTag(show))) {
            trx.add(R.id.container, showFragment, getFragmentTag(show)).commitNowAllowingStateLoss();
        } else {
            trx.show(showFragment).commitNowAllowingStateLoss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void openTaskBar(OpenBottomTabEvent event) {
        dataBinding.bottomTabLayout.setCurrentItem(indexTask);
        EventBus.getDefault().post(new UpdateEvent());

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (System.currentTimeMillis() - exitTime > Constant.EXIT_TIME) {
            Toast.makeText(HomeActivity.this, getString(R.string.home_back), Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void success(UpdateBean updateBean) {
        if (null != updateBean) {
            showUpdateDialog(updateBean);
        }
    }

    @Override
    public void failed(String message) {
        showMessage(message);
    }

    /**
     * @return 版本名
     */
    private String getVersionName() {
        PackageInfo pInfo = null;
        try {
            pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
        return pInfo.versionName;
    }

    private void showUpdateDialog(UpdateBean updateBean) {
        UpdateManager.updateLayoutId = R.layout.update_progress_dialog;
        /*暂不更新*/
        if (0 == updateBean.enforce) {
            new UpdateVersionDialog(HomeActivity.this).setVersionName("更新版本 V" + updateBean.version).setUpdateContent(updateBean.content).setNotUpdateText("暂不更新").setUpdateText("立即更新").setNotUpdateOnClickListener(view -> {
            }).setUpdateOnClickListener(view -> {
                UpdateManager.update(HomeActivity.this, updateBean.version, updateBean.downloadurl, new UpdateCallback() {
                    @Override
                    public void finish() {
                        UpdateManager.release();
                    }

                    @Override
                    public void error(String s) {
                        showMessage("更新失败");
                        UpdateManager.release();
                    }
                });
            }).build().show();
        } else {
            /*强制更新*/
            new UpdateVersionDialog(HomeActivity.this).setVersionName("更新版本 V" + updateBean.version).setUpdateContent(updateBean.content).isForceUpdate(true).setUpdateText("立即更新").setUpdateOnClickListener(view -> {
                UpdateManager.update(HomeActivity.this, updateBean.version, updateBean.downloadurl, new UpdateCallback() {
                    @Override
                    public void finish() {
                        UpdateManager.release();
                    }

                    @Override
                    public void error(String s) {
                        showMessage("更新失败");
                        UpdateManager.release();
                    }
                });
            }).build().show();
        }

    }
}
